import React, { Component } from 'react';

import './index.less';
import { base, promptBox, toast } from 'nc-lightapp-front';
import { hrAjax as proFetch } from 'src/hrpub/common/utils/utils';
import { getQueryCondition } from 'src/hrpub/common/utils/utils';
const searchId = 'ConditionQuery';
const {
    NCModal,
    NCButton,
    NCSelect, NCFormControl, NCTable
} = base;

const { NCOption } = NCSelect;
const {
    Header: NCHeader,
    Body: NCBody,
    Footer: NCFooter
} = NCModal;


class InfoSetting extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    settingInfo = (item) => {
        if (this.props.editStatus) {
            return;
        }
        this.props.update({currentInfoItem: item})
        this.getFormData(item.nodeData.nodeValue.hashValue.m_data_id)
    }
    getFormData = async (meta_id) => {
        const { form } = this.props;
        /*清空表单所有数据*/
        form.EmptyAllFormValue('conditionCard');
        await this.props.update({
            datecontrol: false,
            dateFormat: '', // 选择得日期格式
            prefixValue: '',  // 前缀
            suffixValue: '', // 后缀
            searchData: {}
        })
        return proFetch({
            url: '/nccloud/hrpub/rptdef/QueryAction.do',
            body: {
                meta_data_id: meta_id// '1002Z7100000000046GP',
            }
        })
            .then((res) => {
                if (res.data) {
                    if (res.data.form) {
                        let formData = res.data.form.conditionCard
                        form.setAllFormValue({
                            'conditionCard': formData
                        });
                        // form.setFormStatus('conditionCard', 'edit')
                        this.props.update({
                            datecontrol: res.data.datecontrol,
                            settingDisabled: false
                          }) 
                    } else {
                        this.props.update({
                        settingDisabled: !res.data.editable
                       }) 
                    }
                   
                }
            })
    }
    selectDateFormat = (v) => {
        this.props.update({ dateFormat: v })
    }
    onChange = (e) => {
        this.props.update({ value: e });
    }
    onChangePrefix = (val) => {
        this.props.update({ prefixValue: val })
    }
    onChangeSuffix = (val) => {
        this.props.update({ suffixValue: val })
    }
    // 弹出配置框
    getItemSetting = () => {
        const { meta, search, currentInfoItem } = this.props;
        return proFetch({
            url: '/nccloud/hrpub/rptdef/QueryTemplateInitAction.do',
            body: {
                pk_infoset: currentInfoItem.pid// '1002Z7100000000046GP',
            }
        })
            .then(async(res) => {
                let template = meta.getMeta();
                let currentInfoSetCode = currentInfoItem.code.split('.')[0];
                template['ConditionQuery'].items = res.data[currentInfoSetCode].items;
                // template['ConditionQuery'].items.forEach(item => item.visible=true)
                await meta.setMeta(template, () => { 
                    // 写在这里，第一次弹出后点击确认按钮事件不触发
                    // search.openAdvSearch('ConditionQuery', true) 
                })
                search.openAdvSearch(searchId, true)
            })
    }

    goSearch = (props, data) => {
        let searchData = {
            queryAreaCode: "ConditionQuery", 
            oid: "1001Z710000000003DX7", 
            querytype: "tree",
            querycondition: data
        }
        this.getSettingInfo(searchData)
    }
    getSettingInfo = (searchData) => {
        const { form, selectedRow, search } = this.props;
        this.props.update({ searchData: searchData })
        // formData，meta_data_id，prefix，suffix，dataFormat
        return proFetch({
            url: '/nccloud/hrpub/rptdef/FilterAction.do',
            body: {
                queryFlag: true,
                querycondition: {
                    logic: 'and',
                    conditions: []
                },
                pk_rpt_def: selectedRow.values['pk_rpt_def'].value,
                ...searchData,
                queryAreaCode: searchId,
                pk_infoset: this.props.currentInfoItem.pid,
                oid: '1001Z710000000003DX7',
            }
        })
            .then( (res) => {
                if (res.success) {
                    if (res.data) {
                        form.setFormItemsValue('conditionCard', { 'wheresql': { display: res.data.Wheresql, value: res.data.Wheresql } })
                        form.setFormItemsValue('conditionCard', { 'sqldscrpt': { display: res.data.Sqldscrpt, value: res.data.Sqldscrpt } })
                    }
                }
            })
    }
    onClose = () => {
        // this.props.onClose();
        this.props.update({
            infoSettingVisible: false
        })
        this.props.getSetTableData()
        this.props.update({
            dateFormat: '',
            prefixValue: '',
            suffixValue: '',
            // 表单数据清除
        })
        this.props.form.EmptyAllFormValue('conditionCard')
    }

    submitItemSet = () => {
        const { form, prefixValue, suffixValue, dateFormat, editStatus, currentInfoItem, language, selectedRow } = this.props;
        const allFormValue = form.getAllFormValue('conditionCard');
        // formData，meta_data_id，prefix，suffix，dataFormat
        let meta_data_id = currentInfoItem.nodeData ? currentInfoItem.nodeData.nodeValue.hashValue.m_data_id : currentInfoItem.key;
        return proFetch({
            url: '/nccloud/hrpub/rptdef/FilterAction.do',
            body: {
                formData: { 'model': allFormValue },
                meta_data_id: meta_data_id,
                pk_rpt_def: selectedRow.values['pk_rpt_def'].value,
                prefix: prefixValue,
                suffix: suffixValue,
                dataFormat: dateFormat,
                updateFlag: editStatus, // 修改为true， 新增为false
                // queryFlag: true,
                querycondition: {
                    logic: 'and',
                    conditions: []
                },
                ...this.props.searchData,
                queryAreaCode: searchId,
                oid: '1001Z710000000003DX7',
            }
        })
            .then(async (res) => {
                if (res.success) {
                    toast({
                        color: 'success',
                        content: language["hi6007-000000"] || '保存成功'//
                    });
                    this.onClose()
                }
            })
    }
    render() {
        const {
            visible,
            form,
            language,
            syncTree, 
            onTreeSelect, 
            search,
        } = this.props;

        const { infoSetItemData,
            dateFormatData, 
            datecontrol, 
            editStatus, 
            currentInfoItem,
            prefixValue,
            suffixValue, 
            selectedInfoSet,
            settingDisabled,
            dateFormat } = this.props
        const disable = editStatus? 'disabled': '';

        return (
            <div>
                <NCModal
                    show={visible}
                    onHide={() => this.onClose()}
                    backdrop={'static'}
                    size="lg"
                    dialogClassName="nc-modal-height"
                >
                    <NCHeader
                        closeButton={true}
                    >
                        {language["hi6007-000345"] || '新增条件预置'}
                    </NCHeader>
                    <NCBody className='infoset-content'>
                        <div className='info-set-left'>
                            {/* 左树 */}
                            <div className='info-setting'>
                                {syncTree.createSyncTree({
                                    treeId: 'infoset',
                                    needSearch: false,
                                    needEdit: false,
                                    onSelectEve: onTreeSelect
                                })}
                            </div>
                            <div className='info-set-item'>
                                <div className='info-set-title'>{selectedInfoSet}</div>
                                <ul>
                                    {
                                        infoSetItemData.length > 0 && infoSetItemData.map((item, index) => {
                                            return (
                                                <li className={`${currentInfoItem.key === item.key ? 'active' : ''} ${disable}`} onClick={() => { this.settingInfo(item) }}>{item.name}</li>
                                            )
                                        })
                                    }
                                </ul>
                            </div>
                        </div>

                        <div className='info-set-right'>
                            <div className='info-set-right-form'>
                                {
                                    form.createForm('conditionCard', {
                                        // onBeforeEvent: this.onFormBeforeEvent,
                                        // onAfterEvent: this.onFormAfterEvent
                                    })
                                }

                            </div>
                            <div className='info-set-right-buttons'>
                                <span className='line-wrap'>
                                    <span className={`line`}></span>
                                </span>
                                <NCButton disabled={settingDisabled} onClick={() => this.getItemSetting()}>{language["hi6007-000351"] || '子集取数条件'}</NCButton>
                            </div>
                            <div className='info-set-right-other'>
                                <div className='info-set-right-date'>
                                    <span style={{marginBottom: '5px', fontWeight: '700'}}>{language["hi6007-000350"] || '日期'}</span>
                                    <div>
                                        <span>{language["hi6007-000346"] || '日期格式'}</span>
                                        <NCSelect
                                            className="header-select"
                                            value={dateFormat}
                                            disabled={!datecontrol}
                                            onChange={v => this.selectDateFormat(v)}
                                            // onSelect = {v => this.selectDateFormat(v)}
                                        >
                                            {dateFormatData && dateFormatData.map((item) => {
                                                return (
                                                    <NCOption
                                                        key={item.value}
                                                    >
                                                        {item.display}
                                                    </NCOption>
                                                )
                                            })}
                                        </NCSelect>
                                    </div>
                                </div>
                                <span className='line-wrap'>
                                    <span className={`line`}></span>
                                </span>
                                <div className='info-set-right-text'>
                                    <div style={{marginBottom: '5px', fontWeight: '700'}}>{language["hi6007-000349"] || '扩充文本'}</div>
                                    <div>
                                        <span>{language["hi6007-000347"] || "前缀"}</span>
                                        <NCFormControl
                                            className="demo-input"
                                            value={prefixValue}
                                            onChange={this.onChangePrefix}
                                            size="sm"
                                        />
                                        <span style={{ marginLeft: '20px' }}>{language["hi6007-000348"] ||'后缀'}</span>
                                        <NCFormControl
                                            className="demo-input"
                                            value={suffixValue}
                                            onChange={this.onChangeSuffix}
                                            size="sm"
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </NCBody>
                    <NCFooter>
                        <NCButton
                            colors="primary"
                            onClick={this.submitItemSet}
                        >
                            {language['hi6007-000004']/** 确定*/}
                        </NCButton>
                        <NCButton
                            onClick={() => this.onClose()}
                        >
                            {language['hi6007-000005']/** 取消*/}
                        </NCButton>
                    </NCFooter>
                </NCModal>

                <div style={{
                    display: 'none'
                }}>
                    {search.NCCreateSearch(searchId, {
                        searchBtnName: language['hi6007-000004'] || '确定',
                        onlyShowAdvArea: false,
                        // saveSearchPlan: true,
                        onlyShowSuperBtn: true,
                        hideSearchPlan:true,
                        showAdvSearchPlanBtn:false,
                        syncAdvCondition: false,
                        clickSearchBtn: this.goSearch
                    })}
                </div>
            </div>
        );
    }
}

export default InfoSetting;